import flask
import json
from flask import Flask, request
import types

app = Flask(__name__)


@app.route('/bower_components/<path:path>')
def bower(path):
    return flask.send_from_directory('bower_components', path)


api_dict = {}


def addapi(func):
    api_dict[func.func_name] = func


@app.route('/api/<cmd>', methods=['POST'])
@app.route('/api/<cmd>/<param>', methods=['GET'])
def api(cmd, param=None):
    if request.method == 'POST':
        param = request.json
    else:
        if cmd.find('post')!=-1:
            return 'This request can only use post!'
        param = json.loads(param)
    if isinstance(param, types.ListType):
        return json.dumps(api_dict[cmd](*param))
    return json.dumps(api_dict[cmd](**param))


@app.route('/')
def index():
    return flask.send_file('index.html')


@addapi
def add(a, b):
    return a + b


@addapi
def getlist(n):
    return range(n)


@addapi
def post_islogin(username,password):
    if username=='wkc':
        return 'login success'
    else :
        return 'error'


@addapi
def err(n):
    return 1/0

app.run(debug=True)
